import React, { Component } from 'react'
import { createCode } from './../../util/index'
import api from './../../serve/api'
import styles from './../Register/Register.module.scss'

export default class ResetPwd extends Component {
  constructor(props) {
    super(props)
    this.state = {
      eMail: '',
      inputCode: '',
      code: '',
      message: ''
    }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  componentDidMount = () => {
    this.setState({
      code: createCode()
    })
  }
  

  handleSubmit(event) {
    console.log(this.state)
    event.preventDefault();
    if (this.state.inputCode !== this.state.code) {
      this.setState({
        message: '验证码错误'
      })
      return
    }
    this.findPwdRequest()
  }

  async findPwdRequest() {
    const data = await api.findPwd({ mail: this.state.eMail })
    if (data && data.code === '000000') {
      this.setState({
        message: '修改成功'
      })
      setTimeout(() => {
        this.props.history.goBack()
      }, 1500);
    } else {
      this.setState({
        message: (data && data.message) || ''
      })
    }
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  resetCode() {
    this.setState({
      code: createCode()
    })
  }

  render() {
    return (
      <div className={styles.register}>
        <div className={styles.title}>
          <span style={{ letterSpacing: '2px' }}>重置密码</span>
        </div>
        <div className={styles.register_content}>
          <div className={styles.message}>{this.state.message}</div>
          <form className={styles.form} onSubmit={this.handleSubmit}>
            <div className={styles.form_item}>
              <span>邮箱<em>*</em></span>
              <input
                name="eMail"
                required="required"
                value={this.state.eMail}
                type="email"
                placeholder="请输入邮箱"
                onChange={this.handleInputChange}
              />
            </div>
            <div className={styles.form_item}>
              <span>验证码<em>*</em></span>
              <input
                style={{ width:  157, marginRight: 17 }}
                name="inputCode" 
                required="required"
                value={this.state.inputCode}
                type="text"
                maxLength={6}
                placeholder="请确认验证码"
                onChange={this.handleInputChange}
              />
              <div className={styles.picbox} onClick={() => this.resetCode()}>
                <span>{this.state.code}</span>
              </div>
            </div>
            <div className={styles.form_item}>
              <button type="submit">提交</button>
            </div>
          </form>
        </div>
      </div>
    )
  }
}
